<template>
	<div>
		<el-form class="meal_form" :model="submitForm" :rules="rules" ref="ruleForm" label-width="200px">
			<el-form-item label="套餐名字" prop="title">
				<el-input style="width:100%" v-model="submitForm.title" maxlength="50" show-word-limit
					placeholder="请输入套餐名字，如城市+品牌+型号+产品属性"></el-input>
			</el-form-item>
			<el-form-item label="租期设置" prop="lease_set">
				<el-radio-group v-model="submitForm.lease_set" @change="changeType">
					<el-radio :label="1">按月</el-radio>
					<el-radio :label="2">按天</el-radio>
					<el-radio :label="3">自定义租期</el-radio>
				</el-radio-group>
				<div class="set_wrap">
					<template v-if="submitForm.lease_set==1">
						<div v-if="monthList.length > 0" class="set_form">
							<template v-for="(item, index) in monthList">
								<div :key="index" class="flex align-center item">
									<div>
										<label><i class="required-icon">*</i>租期:</label>
										<el-select v-model="item.lease_time" clearable placeholder="请选择" @change="itemChange(index)">
											<el-option v-for="item in monthSelect" :key="item" :label="item+'个月'" :value="item">
											</el-option>
										</el-select>
									</div>
									<div style="margin-left:40px;margin-right:20px">
										<label><i class="required-icon">*</i>月租金:</label>
										<el-input placeholder="元" v-model="item.lease_price" clearable
											@blur="changeMoneyInput(item, 'lease_price')" @change="itemChange(index)" />
									</div>
									<el-button type="text" @click="removeMonthItem(index)">删除</el-button>
								</div>
							</template>
						</div>
						<el-button icon="el-icon-plus" size="small" type="primary" class="add_btn"
							@click="addMonthItem">添加租期</el-button>
					</template>
					<template v-if="submitForm.lease_set==2">
						<p class="color-999">租期设置超过30天时，租期间隔为30天扣款一次。</p>
						<div v-if="dayList.length > 0" class="set_form day_form">
							<template v-for="(dayItem, dayIndex) in dayList">
								<div :key="dayIndex" class="flex align-center item">
									<div>
										<label><i class="required-icon">*</i>租期:</label>
										<div class="inline-block">
											<el-input style="width:100px" placeholder="请输入" v-model="dayItem.lease_time" clearable
												@input="val=>changeNumberInput(dayItem,'lease_time')" @change="itemChange(dayIndex)" />
											<span class="suffix">天</span>
										</div>
										<span class="color-999" style="margin-left:10px">输入范围：1-365</span>
									</div>
									<div style="margin-left:40px;margin-right:20px">
										<label><i class="required-icon">*</i>日租金:</label>
										<el-input placeholder="元" v-model="dayItem.day_price" clearable @change="itemChange(dayIndex)"
											@blur="changeMoneyInput(dayItem, 'day_price')" />
									</div>
									<el-button type="text" @click="removeDayItem(dayIndex)">删除</el-button>
								</div>
							</template>
						</div>
						<el-button icon="el-icon-plus" size="small" type="primary" class="add_btn"
							@click="addDayItem">添加租期</el-button>
					</template>
					<template v-if="submitForm.lease_set==3">
						<div>
							<p>自定义租期设置<span style="margin-left:20px" class="color-999">在下方栏中选择内容并生成表格</span></p>
							<div class="flex flex-wrap align-center custom_form">
								<div>
									<span class="suffix before"><i class="required-icon">*</i>总租期</span>
									<el-input style="width:100px" placeholder="0-365天" v-model="customForm.lease_days" clearable
										@input="val=>changeNumberInput(customForm,'lease_days')" />
								</div>
								<div>
									<span class="suffix before"><i class="required-icon">*</i>租期间隔</span>
									<el-select style="width:100px" v-model="customForm.withhold_cycle" clearable placeholder="请选择">
										<el-option v-for="(item, index) in intervalList" :key="index" :label="item+'天'" :value="item">
										</el-option>
									</el-select>
								</div>
								<div>
									<span class="suffix before">每期租金</span>
									<el-input class="no_border" style="width:160px" placeholder="请输入" v-model="customForm.lease_price"
										clearable @blur="changeMoneyInput(customForm, 'lease_price')" />
									<span class="suffix">元</span>
								</div>
								<el-button icon="el-icon-plus" size="small" type="primary" style="margin-bottom:10px"
									@click="addCustomItem">生成自定义租期</el-button>
							</div>
							<p class="color-999" style="line-height:23px">1. 租期间隔根据设置总租期生成期数，多余的租赁天数单独生成一个期数。<br />2. 每个租期可单独设置租赁金额。
							</p>
						</div>
						<div class="custom_item" v-for="(customItem, cIndex) in customList" :key="cIndex">
							<p>租期{{cIndex+1}}</p>
							<div class="flex align-center" style="width:800px;position:relative;padding-right:70px">
								<el-table class="table_item" :data="customItem" border>
									<el-table-column align="center" label="期数" width="100px">
										<template slot-scope="scope">
											<span>第{{scope.row.which_period}}期</span>
										</template>
									</el-table-column>
									<el-table-column align="center" label="租赁天数">
										<template slot-scope="scope">
											<span>{{scope.row.lease_days}}天</span>
										</template>
									</el-table-column>
									<el-table-column align="center" label="租期间隔">
										<template slot-scope="scope">
											<span>{{scope.row.withhold_cycle}}天</span>
										</template>
									</el-table-column>
									<el-table-column align="center" width="200">
										<template slot="header">
											<span><i class="required-icon">*</i>每期租金</span>
										</template>
										<template slot-scope="scope">
											<div>
												<el-input style="width:120px;" placeholder="请输入" v-model="scope.row.lease_price" clearable
													@blur="changeMoneyInput(scope.row, 'lease_price')" />
												<span class="suffix">元</span>
											</div>
										</template>
									</el-table-column>
								</el-table>
								<p class="delete_btn">
									<el-button type="text" @click="removeCustomItem(cIndex)">删除</el-button>
								</p>
							</div>
						</div>
					</template>
				</div>
			</el-form-item>
			<el-form-item v-if="rentType==2&&(submitForm.lease_set==2||submitForm.lease_set==1)" label="花呗分期">
				<el-checkbox v-model="submitForm.is_huabei" :true-label="1" :false-label="2">商品支持花呗分期</el-checkbox>
				<p class="tip">注：花呗分期商品成单后并结算后，供应商得租期总金额。了解花呗分期介绍</p>
			</el-form-item>
			<el-form-item v-if="rentType==2&&(submitForm.lease_set==2||submitForm.lease_set==1)&&submitForm.is_huabei==1"
				label="花呗设置">
				<div class="set_wrap">
					<p>批量设置<span style="margin-left:20px" class="color-999">在下方栏中选择内容进行批量填充</span></p>
					<div class="flex flex-wrap align-center custom_form">
						<div>
							<span class="suffix before">花呗3期</span>
							<el-select style="width:120px" v-model="setForm.third" clearable placeholder="请选择">
								<el-option label="商家承担" :value="1"></el-option>
								<el-option label="用户承担" :value="2"></el-option>
								<el-option label="关闭" :value="3"></el-option>
							</el-select>
						</div>
						<div>
							<span class="suffix before">花呗6期</span>
							<el-select style="width:120px" v-model="setForm.sixth" clearable placeholder="请选择">
								<el-option label="商家承担" :value="1"></el-option>
								<el-option label="用户承担" :value="2"></el-option>
								<el-option label="关闭" :value="3"></el-option>
							</el-select>
						</div>
						<div>
							<span class="suffix before">花呗12期</span>
							<el-select style="width:120px" v-model="setForm.twelve" clearable placeholder="请选择">
								<el-option label="商家承担" :value="1"></el-option>
								<el-option label="用户承担" :value="2"></el-option>
								<el-option label="关闭" :value="3"></el-option>
							</el-select>
						</div>
						<el-button size="small" type="primary" @click="quickSet">立即设置</el-button>
					</div>
					<el-table class="set_table" :data="submitForm.huabei_data" border>
						<el-table-column align="center" label="租期设置" width="100px">
							<template slot-scope="scope">
								<span>{{scope.row.lease_term?(scope.row.lease_term+(submitForm.lease_set==1?'个月':'天')):''}}</span>
							</template>
						</el-table-column>
						<el-table-column align="center" label="花呗总金额" prop="rent_total" />
						<el-table-column align="center">
							<template slot="header">
								<span><i class="required-icon">*</i>花呗3期承担-承担金额</span>
							</template>
							<template slot-scope="scope">
								<el-select style="width:120px" v-model="scope.row.three_bear" clearable placeholder="请选择"
									@change="changeHbBear(scope.row.three_bear, scope.row, 'three_fee')">
									<el-option label="商家承担" :value="1"></el-option>
									<el-option label="用户承担" :value="2"></el-option>
									<el-option label="关闭" :value="3"></el-option>
								</el-select>
								<span class="inline-block text-left"
									style="min-width:60px;margin-left:10px">{{scope.row.three_fee?'￥'+scope.row.three_fee:''}}</span>
							</template>
						</el-table-column>
						<el-table-column align="center">
							<template slot="header">
								<span><i class="required-icon">*</i>花呗6期承担-承担金额</span>
							</template>
							<template slot-scope="scope">
								<el-select style="width:120px" v-model="scope.row.six_bear" clearable placeholder="请选择"
									@change="changeHbBear(scope.row.six_bear, scope.row, 'six_fee')">
									<el-option label="商家承担" :value="1"></el-option>
									<el-option label="用户承担" :value="2"></el-option>
									<el-option label="关闭" :value="3"></el-option>
								</el-select>
								<span class="inline-block text-left"
									style="min-width:60px;margin-left:10px">{{scope.row.six_fee?'￥'+scope.row.six_fee:''}}</span>
							</template>
						</el-table-column>
						<el-table-column align="center">
							<template slot="header">
								<span><i class="required-icon">*</i>花呗12期承担-承担金额</span>
							</template>
							<template slot-scope="scope">
								<el-select style="width:120px" v-model="scope.row.twelve_bear" clearable placeholder="请选择"
									@change="changeHbBear(scope.row.twelve_bear, scope.row, 'twelve_fee')">
									<el-option label="商家承担" :value="1"></el-option>
									<el-option label="用户承担" :value="2"></el-option>
									<el-option label="关闭" :value="3"></el-option>
								</el-select>
								<span class="inline-block text-left"
									style="min-width:60px;margin-left:10px">{{scope.row.twelve_fee?'￥'+scope.row.twelve_fee:''}}</span>
							</template>
						</el-table-column>
					</el-table>
					<div class="flex color-999" style="line-height:1;margin-top:14px"><span>注：</span>
						<p>1、花呗分期每笔均产生分期手续费，商户可选择用户或自己承担或者关闭当前租期花呗功能（无法共同承担）。<br />2、花呗手续费承担方选择后，将自动计算承担金额。
							<el-popover placement="right" width="400" trigger="hover">
								<div class="fee_exp">
									<h5 style="margin-bottom:14px">手续费花呗分期费率表</h5>
									<el-table class="fee_table" :data="feeData" border>
										<el-table-column align="center" label="期数" prop="num" />
										<el-table-column align="center" label="商户承担" prop="merchant" />
										<el-table-column align="center" label="用户承担" prop="user" />
									</el-table>
								</div>
								<el-button type="text" slot="reference">查看费率表</el-button>
							</el-popover>
						</p>
					</div>
				</div>
			</el-form-item>
			<el-form-item label="起租日设置">
				<el-select v-model="submitForm.start_date" clearable placeholder="请选择">
					<el-option v-for="(item, index) in startDateSelect" :key="index" :label="item+'天'" :value="item">
					</el-option>
				</el-select>
				<p class="tip">起租日为租赁合同起租时间，默认起租日为下单日3天后。</p>
			</el-form-item>
			<el-form-item label="数量" prop="quantity">
				<el-input placeholder="库存数量" v-model="submitForm.quantity" clearable
					@input="val=>changeNumberInput(submitForm,'quantity')" />
			</el-form-item>
			<el-form-item label="押金" prop="foregift">
				<div>
					<el-input class="suffix_input" placeholder="请输入押金" v-model="submitForm.foregift" clearable
						@blur="changeMoneyInput(submitForm, 'foregift')" />
					<span class="suffix">元</span>
				</div>
				<p class="tip">当前商品合同类型为随租随还，芝麻信用授权可扣款金额=商品套餐押金+总租金</p>
			</el-form-item>
			<el-form-item label="是否买断" prop="is_buy_out">
				<el-radio v-model="submitForm.is_buy_out" :label="1">是</el-radio>
				<el-radio v-model="submitForm.is_buy_out" :label="2">否</el-radio>
			</el-form-item>
			<el-form-item label="官网价格" prop="price">
				<div>
					<el-input class="suffix_input" placeholder="请输入官网价格" v-model="submitForm.price" clearable
						@blur="changeMoneyInput(submitForm, 'price')" />
					<span class="suffix">元</span>
				</div>
				<!-- <p class="tip">商家需设置销售价格，租户在租期中，买断价格=销售价格-累计支付的租期金额，商家也可根据实际情况在订单单独设置买断金额。</p> -->
			</el-form-item>
			<!-- <el-form-item
        label="买断价"
        prop="buyout_amount"
      >
        <div>
          <el-input
            class="suffix_input"
            placeholder="请输入买断价"
            v-model="submitForm.buyout_amount"
            clearable
            @blur="changeMoneyInput(submitForm, 'buyout_amount')"
          />
          <span class="suffix">元</span>
        </div>
      </el-form-item> -->
		</el-form>
		<div class="fix-footer-btns">
			<div class="flex justify-center align-center">
				<label style="margin-right:20px"><i class="required-icon" style="margin-right:5px">*</i>商品审核后状态:</label>
				<el-radio v-model="status" :label="1">商品上架</el-radio>
				<el-radio v-model="status" :label="2">商品下架</el-radio>
			</div>
			<el-divider></el-divider>
			<div>
				<template v-if="$route.name==='goodsAdd'">
					<el-button size="small" v-if="$hasMethod('#saveMealDraft')" @click="saveToDraft">保存草稿</el-button>
					<el-button size="small" class="blue_border" @click="returnTab">返回</el-button>
					<el-button size="small" type="primary" v-if="$hasMethod('#addMeal')" @click="addMeal()">添加套餐</el-button>
					<el-button size="small" type="warning" v-if="$hasMethod('#publish')" @click="addMeal(true)">发布商品</el-button>
				</template>
				<template v-else>
					<el-button size="small" @click="$router.go(-1)">返回</el-button>
					<el-button v-if="$hasMethod('#saveMeal')" size="small" type="primary" @click="save">保存</el-button>
					<el-button v-if="$hasMethod('#submit')&&!hideAuditBtn" size="small" type="warning"
						@click="submitAudit">提交审核</el-button>
				</template>
			</div>
		</div>
	</div>
</template>

<script>
	import {
		getParameterList,
		addSetmeal,
		getGoodsSetmealInfo,
		editGoodsSetmeal,
		goodsSubmitReview
	} from "@/api/goods";
	export default {
		props: ['currentMeal', 'editId', 'draftId'],
		data() {
			return {
				submitForm: {
					setmeal_id: "",
					title: "",
					lease_set: 1,
					is_huabei: 2,
					huabei_data: [{
						lease_term: "",
						rent_total: "",
						three_bear: "",
						three_fee: "",
						six_bear: "",
						six_fee: "",
						twelve_bear: "",
						twelve_fee: ""
					}],
					quantity: "",
					foregift: "",
					is_buy_out: 1,
					price: "",
					buyout_amount: "",
					start_date: ""
				},
				rules: {
					title: [{
						required: true,
						message: '请输入套餐名字',
						trigger: 'blur'
					}, ],
					huabei_data: [{
						required: true,
						message: '请填写花呗设置',
						trigger: 'change'
					}],
					quantity: [{
						required: true,
						message: '请输入库存数量',
						trigger: 'blur'
					}, ],
					foregift: [{
						required: true,
						message: '请输入押金',
						trigger: 'blur'
					}, ],
					is_buy_out: [{
						required: true,
						message: '请选择是否买断',
						trigger: 'change'
					}, ],
					price: [{
						required: true,
						message: '请输入销售价格',
						trigger: 'blur'
					}, ],
					// buyout_amount: [
					//   { required: true, message: '请输入买断价', trigger: 'blur' },
					// ],
					lease_set: [{
						required: true,
						message: '请选择租期设置',
						trigger: 'change'
					}, ]
				},
				monthList: [{
					lease_time: null,
					lease_price: ""
				}], // 按月租期设置
				monthSelect: [], // 可选月租期
				dayList: [{
					lease_time: "",
					lease_price: "",
					day_price: ""
				}], // 按天租期设置
				customList: [], //自定义租期
				customForm: {
					lease_days: "",
					withhold_cycle: "",
					lease_price: ""
				},
				intervalList: [], // 可选租期间隔
				setForm: {
					third: "",
					sixth: "",
					twelve: ""
				},
				feeData: [{
						num: 3,
						merchant: '1.80%',
						user: '2.30%'
					},
					{
						num: 6,
						merchant: '4.50%',
						user: '4.50%'
					},
					{
						num: 12,
						merchant: '7.50%',
						user: '7.50%'
					}
				],
				startDateSelect: [],
				rentType: 0,
				goodsId: "",
				status: 2,
				hideAuditBtn: false
			}
		},
		methods: {
			// 提交审核
			submitAudit() {
				goodsSubmitReview(this.goodsId).then(res => {
					this.$router.push({
						name: 'goodsSuccess',
						params: {
							goodsId: this.goodsId,
							isEdit: true
						}
					});
				})
			},
			// 保存草稿
			saveToDraft() {
				if (!this.goodsId) {
					this.$message({
						message: "请先提交商品基础信息",
						type: "warning"
					});
					return;
				}
				if (!this.submitForm.title) {
					this.$message({
						message: "套餐名字不能为空",
						type: "warning"
					});
					return;
				}
				const params = {
					goods_id: this.goodsId,
					spec: [],
					...this.submitForm,
					status: this.status,
					operation_type: 1
				};
				if (this.submitForm.lease_set == 1) {
					params.spec = [...this.monthList];
				} else if (this.submitForm.lease_set == 2) {
					params.spec = [...this.dayList];
				} else {
					params.spec = [...this.customList];
				}
				if (params.setmeal_id) {
					// 存在套餐id，编辑套餐
					editGoodsSetmeal(params).then(res => {
						this.saveStorage();
						this.$message({
							message: "保存成功",
							type: "success"
						});
					})
				} else {
					// 不存在套餐id，添加套餐
					delete params.setmeal_id;
					addSetmeal(params).then(res => {
						this.submitForm.setmeal_id = res.setmeal_id;
						this.saveStorage();
						this.$message({
							message: "保存成功",
							type: "success"
						});
					})
				}
			},
			// 返回上一标签
			returnTab() {
				if (this.currentMeal == 1) {
					this.$emit('setTab', 'base');
				} else {
					this.$emit('setTab', 'meal' + (this.currentMeal - 1));
				}
			},
			save() {
				const that = this;
				this.$confirm('商品信息变更需要平台审核，审核时间1个工作日，确定修改商品？', '修改商品', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
				}).then(() => {
					that.$refs['ruleForm'].validate((valid) => {
						if (valid) {
							if (!that.validCheck()) {
								return;
							}
							const params = {
								goods_id: that.goodsId,
								spec: [],
								...that.submitForm,
								status: that.status,
								operation_type: 3
							};
							if (that.submitForm.lease_set == 1) {
								params.spec = [...that.monthList];
							} else if (that.submitForm.lease_set == 2) {
								params.spec = [...that.dayList];
							} else {
								params.spec = [...that.customList];
							}
							if (this.editId) {
								editGoodsSetmeal(params).then(res => {
									that.$message({
										message: "保存成功",
										type: "success"
									});
									that.$router.back();
								})
							} else {
								delete params.setmeal_id;
								addSetmeal(params).then(res => {
									that.$message({
										message: "添加成功",
										type: "success"
									});
									that.$router.back();
								})
							}
						} else {
							that.$message({
								message: "请检查表单错误",
								type: "error"
							});
							return false;
						}
					});
				}).catch(() => {});
			},
			// 表单校验
			validCheck() {
				// 校验租期设置
				if (this.submitForm.lease_set == 1) {
					if (this.monthList.length === 0) {
						this.$message({
							message: "租期设置不能为空",
							type: "warning"
						});
						return false;
					}
					// for (let item of this.monthList) {
					//   if (!item.lease_time || !item.lease_price) {
					//     this.$message({
					//       message: "租期设置必填项不能为空",
					//       type: "warning"
					//     });
					//     return false;
					//   }
					// }
					const arr = this.monthList.map(k => k.lease_time);
					const uniqueArr = [...new Set(arr)];
					if (uniqueArr.length < arr.length) {
						this.$message({
							message: "租期设置租期不能重复",
							type: "warning"
						});
						return false;
					}
				} else if (this.submitForm.lease_set == 2) {
					if (this.dayList.length === 0) {
						this.$message({
							message: "租期设置不能为空",
							type: "warning"
						});
						return false;
					}
					// for (let item of this.dayList) {
					//   if (!item.lease_time || !item.lease_price) {
					//     this.$message({
					//       message: "租期设置必填项不能为空",
					//       type: "warning"
					//     });
					//     return false;
					//   }
					// }
					const arr = this.dayList.map(k => k.lease_time);
					const uniqueArr = [...new Set(arr)];
					if (uniqueArr.length < arr.length) {
						this.$message({
							message: "租期设置租期不能重复",
							type: "warning"
						});
						return false;
					}
				} else {
					if (this.customList.length === 0) {
						this.$message({
							message: "租期设置不能为空",
							type: "warning"
						});
						return false;
					}
					for (let item of this.customList) {
						for (let row of item) {
							if (!row.lease_price) {
								this.$message({
									message: "租期设置每期租金不能为空",
									type: "warning"
								});
								return false;
							}
						}
					}
				}
				if (this.submitForm.is_huabei == 1) {
					// 开启花呗，校验花呗设置数组
					if (this.submitForm.huabei_data.length === 0) {
						this.$message({
							message: "花呗设置不能为空",
							type: "warning"
						});
						return false;
					}
					for (let item of this.submitForm.huabei_data) {
						if (!item.three_bear || !item.six_bear || !item.twelve_bear) {
							this.$message({
								message: "花呗设置承担选项不能为空",
								type: "warning"
							});
							return false;
						}
					}
				}
				return true
			},
			// 添加套餐
			addMeal(isPublish) {
				// 判断是否有商品id
				if (!this.goodsId) {
					this.$message({
						message: "请先提交商品基础信息",
						type: "warning"
					});
					return;
				}
				// 提交当前表单
				this.$refs['ruleForm'].validate((valid) => {
					if (valid) {
						if (!this.validCheck()) {
							return;
						}
						const params = {
							goods_id: this.goodsId,
							spec: [],
							...this.submitForm,
							status: this.status,
							operation_type: (isPublish ? 2 : 3)
						};
						if (this.submitForm.lease_set == 1) {
							params.spec = [...this.monthList];
						} else if (this.submitForm.lease_set == 2) {
							params.spec = [...this.dayList];
						} else {
							params.spec = [...this.customList];
						}
						if (params.setmeal_id) {
							// 存在套餐id，编辑套餐
							editGoodsSetmeal(params).then(res => {
								if (isPublish) {
									this.$router.push({
										name: 'goodsSuccess',
										params: {
											goodsId: this.goodsId
										}
									});
								} else {
									this.saveStorage();
									this.$emit('addTab');
								}
							})
						} else {
							// 不存在套餐id，添加套餐
							delete params.setmeal_id;
							addSetmeal(params).then(res => {
								if (isPublish) {
									this.$router.push({
										name: 'goodsSuccess',
										params: {
											goodsId: this.goodsId
										}
									});
								} else {
									this.submitForm.setmeal_id = res.setmeal_id;
									this.saveStorage();
									this.$emit('addTab');
								}
							})
						}
					} else {
						this.$message({
							message: "请检查表单错误",
							type: "error"
						});
						return false;
					}
				});
			},
			// 切换租期设置类型
			changeType(val) {
				// 切换重置
				this.submitForm.is_huabei = 2;
				this.submitForm.huabei_data = [{
					lease_term: "",
					rent_total: "",
					three_bear: "",
					three_fee: "",
					six_bear: "",
					six_fee: "",
					twelve_bear: "",
					twelve_fee: ""
				}];
				this.monthList = [{
					lease_time: null,
					lease_price: ""
				}];
				this.dayList = [{
					lease_time: "",
					lease_price: "",
					day_price: ""
				}];
				this.customForm = {
					lease_days: "",
					withhold_cycle: "",
					lease_price: ""
				};
			},
			quickSet() {
				this.submitForm.huabei_data.forEach(element => {
					if (this.setForm.third) {
						element.three_bear = this.setForm.third;
					}
					if (this.setForm.sixth) {
						element.six_bear = this.setForm.sixth;
					}
					if (this.setForm.twelve) {
						element.twelve_bear = this.setForm.twelve;
					}
					this.setHbFee(element);
				});
				// 清空上次设置
				this.setForm = {
					third: "",
					sixth: "",
					twelve: ""
				}
			},
			// 花呗承担切换
			changeHbBear(val, obj, key) {
				if (val == 1 || val == 2) {
					this.setHbFee(obj);
				} else {
					obj[key] = "";
				}
			},
			// 保留两位小数
			toFix2(calVal) {
				return (Math.round(calVal * 100) / 100).toFixed(2);
			},
			// 设置花呗分期承担金额
			setHbFee(tableItem) {
				if (tableItem.three_bear == 1) {
					tableItem.three_fee = this.toFix2(0.018 * tableItem.rent_total);
				}
				if (tableItem.three_bear == 2) {
					tableItem.three_fee = this.toFix2(0.023 * tableItem.rent_total);
				}
				if (tableItem.six_bear == 1) {
					tableItem.six_fee = this.toFix2(0.045 * tableItem.rent_total);
				}
				if (tableItem.six_bear == 2) {
					tableItem.six_fee = this.toFix2(0.045 * tableItem.rent_total);
				}
				if (tableItem.twelve_bear == 1) {
					tableItem.twelve_fee = this.toFix2(0.075 * tableItem.rent_total);
				}
				if (tableItem.twelve_bear == 2) {
					tableItem.twelve_fee = this.toFix2(0.075 * tableItem.rent_total);
				}
			},
			// 按月租期项更改
			itemChange(index) {
				const {
					lease_time,
					lease_price
				} = (this.submitForm.lease_set == 1 ? this.monthList[index] : this.dayList[index]);
				if (!lease_time || !lease_price) {
					return;
				}
				const hbSetItem = this.submitForm.huabei_data[index];
				hbSetItem.lease_term = lease_time;
				hbSetItem.rent_total = (parseFloat(lease_price) * lease_time).toFixed(2);
				this.setHbFee(hbSetItem);
			},
			changeNumberInput(obj, key) {
				const pattern = /^[1-9][0-9]*$/ // 正整数的正则表达式
				// 不符合正整数时
				if (!pattern.test(obj[key])) {
					// input 框绑定的内容为空
					obj[key] = ''
				}
			},
			changeMoneyInput(obj, key) {
				const pattern = /^[0-9]+([.]{1}[0-9]{1,2})?$/; // 正数的正则表达式
				// 不符合正数时
				if (!pattern.test(obj[key])) {
					// input 框绑定的内容为空
					obj[key] = '';
				}
			},
			// 删除自定义租期
			removeCustomItem(index) {
				this.customList.splice(index, 1);
			},
			// 新增自定义租期
			addCustomItem() {
				if (!this.customForm.lease_days || !this.customForm.withhold_cycle) {
					this.$message({
						message: "总租期、租期间隔不能为空",
						type: "warning"
					});
					return;
				}
				const periodTotal = Math.ceil(parseInt(this.customForm.lease_days) / parseInt(this.customForm.withhold_cycle));
				let data = [];
				for (let index = 1; index <= periodTotal; index++) {
					let obj = {
						which_period: index,
						lease_days: 0,
						withhold_cycle: this.customForm.withhold_cycle,
						lease_price: this.customForm.lease_price ? this.customForm.lease_price : 0
					}
					if (index * parseInt(this.customForm.withhold_cycle) <= this.customForm.lease_days) {
						obj.lease_days = this.customForm.withhold_cycle;
					} else {
						obj.lease_days = parseInt(this.customForm.lease_days) % parseInt(this.customForm.withhold_cycle);
					}
					data.push(obj);
				}
				this.customList.push(data);
				// 清空表单
				this.customForm = {
					lease_days: "",
					withhold_cycle: "",
					lease_price: ""
				}
			},
			// 删除天租期
			removeDayItem(index) {
				this.dayList.splice(index, 1);
				this.submitForm.huabei_data.splice(index, 1);
			},
			// 新增天租期
			addDayItem() {
				this.dayList.push({
					lease_time: "",
					lease_price: "",
					day_price: ""
				})
				this.submitForm.huabei_data.push({
					lease_term: "",
					rent_total: "",
					three_bear: "",
					three_fee: "",
					six_bear: "",
					six_fee: "",
					twelve_bear: "",
					twelve_fee: ""
				});
			},
			// 删除月租期
			removeMonthItem(index) {
				this.monthList.splice(index, 1);
				this.submitForm.huabei_data.splice(index, 1);
			},
			// 新增月租期
			addMonthItem() {
				this.monthList.push({
					lease_time: null,
					lease_price: ""
				});
				this.submitForm.huabei_data.push({
					lease_term: "",
					rent_total: "",
					three_bear: "",
					three_fee: "",
					six_bear: "",
					six_fee: "",
					twelve_bear: "",
					twelve_fee: ""
				});
			},
			init() {
				getParameterList().then(res => {
					this.startDateSelect = res.start_date || [];
					this.intervalList = res.withhold_cycle || [];
					this.monthSelect = res.lease_term_month || [];
				})
			},
			getData() {
				this.submitForm = {
					setmeal_id: "",
					title: "",
					lease_set: 1,
					is_huabei: 2,
					huabei_data: [{
						lease_term: "",
						rent_total: "",
						three_bear: "",
						three_fee: "",
						six_bear: "",
						six_fee: "",
						twelve_bear: "",
						twelve_fee: ""
					}],
					quantity: "",
					foregift: "",
					is_buy_out: 1,
					price: "",
					start_date: ""
				};
				this.monthList = [{
					lease_time: null,
					lease_price: ""
				}];
				this.dayList = [{
					lease_time: "",
					lease_price: "",
					day_price: ""
				}];
				this.customList = [];
				if (sessionStorage.getItem('mealInfo')) {
					const list = JSON.parse(sessionStorage.getItem('mealInfo'));
					if (list[this.currentMeal - 1]) {
						const data = list[this.currentMeal - 1];
						this.submitForm = {
							...data.formData
						};
						this.monthList = [...data.monthList];
						this.dayList = [...data.dayList];
						this.customList = [...data.customList];
					}
				}
				this.status = parseInt(sessionStorage.getItem('goodsStatus'));
			},
			saveStorage(index) {
				const params = {
					formData: this.submitForm,
					monthList: this.monthList,
					dayList: this.dayList,
					customList: this.customList
				};
				const list = sessionStorage.getItem('mealInfo') ? JSON.parse(sessionStorage.getItem('mealInfo')) : [];
				list[index - 1] = {
					...params
				};
				sessionStorage.setItem('mealInfo', JSON.stringify(list));
				sessionStorage.setItem('goodsStatus', this.status);
			},
			getInfo() {
				getGoodsSetmealInfo(this.editId).then(res => {
					this.hideAuditBtn = res.ischeck == 3;
					for (let key in this.submitForm) {
						if (key === 'huabei_data') {
							if (res.is_huabei == 1) {
								this.submitForm[key] = res[key];
							}
						} else if (key === 'setmeal_id') {
							this.submitForm[key] = res.id;
						} else {
							this.submitForm[key] = res[key];
						}
					}
					this.rentType = res.pact_type;
					this.status = res.goods_status;
					if (res.lease_set == 1) {
						this.monthList = res.spec;
						if (this.submitForm.is_huabei == 2) {
							for (let index in this.monthList) {
								const {
									lease_time,
									lease_price
								} = this.monthList[index];
								const rentTotal = (parseFloat(lease_price) * lease_time).toFixed(2);
								if (index == 0) {
									this.submitForm.huabei_data[index].lease_term = lease_time;
									this.submitForm.huabei_data[index].rent_total = rentTotal;
								} else {
									this.submitForm.huabei_data.push({
										lease_term: lease_time,
										rent_total: rentTotal,
										three_bear: "",
										three_fee: "",
										six_bear: "",
										six_fee: "",
										twelve_bear: "",
										twelve_fee: ""
									});
								}
							}
						}
					} else if (res.lease_set == 2) {
						this.dayList = res.spec;
						if (this.submitForm.is_huabei == 2) {
							for (let index in this.dayList) {
								const {
									lease_time,
									lease_price,
									day_price
								} = this.dayList[index];
								const rentTotal = (parseFloat(lease_price) * lease_time).toFixed(2);
								if (index == 0) {
									this.submitForm.huabei_data[index].lease_term = lease_time;
									this.submitForm.huabei_data[index].rent_total = rentTotal;
								} else {
									this.submitForm.huabei_data.push({
										lease_term: lease_time,
										rent_total: rentTotal,
										three_bear: "",
										three_fee: "",
										six_bear: "",
										six_fee: "",
										twelve_bear: "",
										twelve_fee: ""
									});
								}
							}
						}
					} else {
						this.customList = res.spec;
					}
				})
			}
		},
		watch: {
			currentMeal(val, oldVal) {
				this.getData();
			}
		},
		mounted() {
			this.init();
			this.$nextTick(() => {
				if (this.$route.name === 'goodsMeal') {
					this.goodsId = this.$route.params.goodsId;
					if (this.editId) {
						this.getInfo();
					} else {
						this.rentType = this.$route.params.pact_type;
					}
				} else {
					this.rentType = JSON.parse(sessionStorage.getItem('baseInfo')) ? JSON.parse(sessionStorage.getItem(
						'baseInfo')).formData.pact_type : 0;
					this.goodsId = sessionStorage.getItem('goodsId') || "";
					this.getData();
				}
			});
		},
		beforeDestroy() {
			if (this.$route.name === 'goodsAdd') {
				this.saveStorage(this.currentMeal);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.meal_form {
		padding: 30px 120px 30px 0;
	}

	.set_wrap {
		padding: 20px;
		background-color: #fafafa;
	}

	.set_form {
		border-bottom: 1px dashed #cdcdcd;
		margin-bottom: 16px;

		.item {
			margin-bottom: 16px;
		}

		.el-select,
		.el-input {
			width: 160px;
		}
	}

	label {
		margin-right: 14px;
	}

	.required-icon {
		margin-right: 3px;
	}

	.add_btn {
		margin-left: 50px;
	}

	.suffix {
		background: #f5f5f5;
		border: 1px solid #dcdfe6;
		border-radius: 0 4px 4px 0;
		height: 40px;
		display: inline-block;
		padding: 0 8px;
		box-sizing: border-box;
		border-left: none;
		line-height: 38px;
	}

	.suffix.before {
		border-left: 1px solid #dcdfe6;
		border-right: none;
		border-radius: 4px 0 0 4px;
	}

	.day_form {
		/deep/.el-input__inner {
			border-radius: 4px 0 0 4px;
		}
	}

	.custom_form {
		margin-top: 8px;
		margin-bottom: 8px;

		/deep/.el-input__inner,
		.el-select {
			border-radius: 0 4px 4px 0;
		}

		.no_border /deep/.el-input__inner {
			border-radius: 0;
		}

		&>div {
			margin-right: 10px;
			margin-bottom: 10px;
		}
	}

	.custom_item+.custom_item {
		border-top: 1px dashed #cdcdcd;
		margin-top: 20px;
	}

	.table_item {
		/deep/th {
			padding: 0;
		}

		.suffix {
			height: 30px;
			line-height: 28px;
		}

		/deep/.el-input__inner {
			border-radius: 4px 0 0 4px;
		}

		/deep/.el-input__icon {
			line-height: 30px;
		}
	}

	.suffix_input {
		/deep/.el-input__inner {
			border-radius: 4px 0 0 4px;
		}
	}

	.delete_btn {
		position: absolute;
		right: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
		width: 70px;
		border: 1px solid #ebeef5;
		border-left: none;
		background-color: #ffffff;
	}

	.tip {
		color: #999999;
		line-height: 35px;
	}

	.set_table {
		/deep/th {
			padding: 0;
		}

		/deep/.el-input__icon {
			line-height: 30px;
		}
	}

	.fix-footer-btns {
		.el-divider {
			background-color: #eeeeee;
			width: 95%;
			margin: 15px auto;
		}
	}
</style>